/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react-native/no-inline-styles */
import React, {useState, useEffect} from 'react';
import {
  TabController,
  View,
  Colors,
  SegmentedControl,
  Image,
  TouchableOpacity,
} from 'react-native-ui-lib';
import {connect} from 'react-redux';
import Input from '@/components/Input';
import {get} from '@/utils/request';
import {useRequest} from 'ahooks';
import List from '@/components/List';
import ProjectIcon from '@/components/ProjectIcon';

const conf = {
  0: {
    key: 'undo',
    text: '未开始',
  },
  1: {
    key: 'doing',
    text: '进行中',
  },
  2: {
    key: 'done',
    text: '已完成',
  },
};

function Home({navigation, appTheme, curProject}) {
  const Prefix = global.file;

  const [index, setIndex] = useState(null);
  const [search, setSearch] = useState();
  const [columns, setColumns] = useState({});
  const [num, setNum] = useState({});
  const [rerender, setRerender] = useState(true);

  // useEffect(() => {
  //   navigation.navigate('Audit');
  // }, []);

  let searchprops = {
    placeholder: '编号/标题',
    value: search,
    lefticon: 'search1',
    allowClear: true,
    onChange: val => {
      setSearch(val);
    },
    onSubmitEditing: async () => {
      //search
    },
    size: 'small',
    containwidth: '40%',
  };

  //格式化文档+前端筛选
  function formatResult(res) {
    const formatedData = {};
    if (res?.length > 0) {
      res?.forEach(item => {
        const filterItem = item?.itemList?.filter(it => {
          return true;
        });

        if (item.status === 0) {
          setNum(s => ({
            ...s,
            undo: filterItem?.length,
          }));
          formatedData.undo = {
            ...item,
            itemList: filterItem,
          };
        } else if (item.status === 1) {
          setNum(s => ({
            ...s,
            doing: filterItem?.length,
          }));
          formatedData.doing = {
            ...item,
            itemList: filterItem,
          };
        } else if (item.status === 2) {
          setNum(s => ({
            ...s,
            done: filterItem?.length,
          }));
          formatedData.done = {
            ...item,
            itemList: filterItem,
          };
        }
      });
      setColumns(formatedData);
    }
  }

  //接口
  const {data, refreshAsync, loading} = useRequest(
    async () => {
      let res = await get('/item', {
        projectId: curProject?.id,
        type: index,
        keyWord: search,
      });
      return res?.data?.dataList;
    },
    {
      refreshDeps: [index, search, curProject],
    },
  );

  useEffect(() => {
    formatResult(data);
  }, [data]);

  const extraprops = {
    refreshAsync,
    loading,
  };

  useEffect(() => {
    setRerender(false);
    setTimeout(() => {
      setRerender(true);
    }, 10);
  }, [appTheme]);

  return (
    <View
      flex-1
      style={{
        backgroundColor: Colors.backgroundColor,
      }}>
      <View padding-12 paddingB-0 row center style={{gap: 10}}>
        <ProjectIcon />
        <Input
          {...searchprops}
          containerStyle={{backgroundColor: Colors.colorCardBg}}
        />
        <View flex-1>
          <SegmentedControl
            activeColor={Colors.primaryColor}
            outlineColor={Colors.primaryColor}
            activeBackgroundColor={Colors.colorBgSecondary}
            backgroundColor={Colors.colorBgSecondary}
            style={{
              borderColor: Colors.backgroundColor,
            }}
            initialIndex={0}
            onChangeIndex={i => {
              setIndex(i === 1 ? 2 : i === 2 ? 1 : null);
            }}
            segments={[{label: '全部'}, {label: '缺陷'}, {label: '任务'}]}
            borderRadius={10}
          />
        </View>
      </View>
      <View flex-1>
        <TabController
          items={Object.entries(conf)?.map(([key, value]) => ({
            label: value.text + ' ' + (num[value.key] ?? ''),
          }))}
          asCarousel={true}>
          {rerender && (
            <TabController.TabBar
              enableShadows
              spreadItems
              labelColor={Colors.colorTextBase}
              selectedLabelColor={Colors.primaryColor}
              indicatorStyle={{
                backgroundColor: Colors.primaryColor,
              }}
              backgroundColor={Colors.backgroundColor}
            />
          )}
          <TabController.PageCarousel flex-1>
            <TabController.TabPage index={0}>
              <List
                appTheme={appTheme}
                data={columns?.undo?.itemList ?? []}
                {...extraprops}
              />
            </TabController.TabPage>
            <TabController.TabPage index={1} lazy>
              <List
                appTheme={appTheme}
                data={columns?.doing?.itemList ?? []}
                {...extraprops}
              />
            </TabController.TabPage>
            <TabController.TabPage index={2} lazy>
              <List
                appTheme={appTheme}
                data={columns?.done?.itemList ?? []}
                {...extraprops}
              />
            </TabController.TabPage>
          </TabController.PageCarousel>
        </TabController>
      </View>
    </View>
  );
}
const mapStateToProps = state => {
  return {
    appTheme: state.appTheme,
    curProject: state.curProject,
  };
};

export default connect(mapStateToProps)(Home);
